"use strict"
/// <reference path="../../index.d.ts" />
const Controller = require("egg").Controller
const {sendStat} = require("../extend/helper")

class MsgController extends Controller {
	constructor(ctx) {
		super(ctx)
		this.constant = this.config.constant
		this.KeyWord = this.app.model.KeyWord
		this.UserKfMsg = this.app.model.UserKfMsg
		this.UserKfMsgV = this.app.model.UserKfMsgV
		this.ApplicationUser = this.app.model.ApplicationUser
	}

	async  upsertKeyWord() {
		let {ctx, KeyWord} = this
		let body = ctx.request.body
		this.ctx.validate({
			id: {
				required: false,
				type: "pintstr"
			},
			aid: "numstr",
			key_name: "string",
			trigger_key: "string",
			trigger_type: "numstr",
			stat: ["0", "1"],
			response_type: ["1", "2", "3"],
			respone_set: "jsonObject",
			edit: ["0", "1"]// 是否为编辑模式
		}, body)
		body.edit = Number(body.edit)
		body.respone_set = JSON.parse(body.respone_set)
		var {id, aid, key_name, trigger_key, trigger_type, stat, response_type, respone_set} = body
		let dealstat = false
		let val
		if (body.edit == 1 && body.id != undefined) {
			[stat, val] = await KeyWord.update({key_name, trigger_key, trigger_type, stat, response_type, respone_set, update_at: Date.now()}, {
				where: {
					id
				}
			})
		} else if (body.edit == 0) {
			val = await KeyWord.create({
				aid, key_name, trigger_key, trigger_type, stat, response_type, respone_set, update_at: Date.now()
			})
			stat = Boolean(val)
		}
		else {
			let errors = [{message: "edit 为1 ,且 id 必须为数字 ,", code: "invalid", field: "id"}]
			ctx.throw(422, "Validation Failed", {
				code: "invalid_param",
				errors,
			})
		}
		this.app.cache.keyWord = undefined
		ctx.body = {stat: dealstat, val}
	}

	/**
 * 查找所有关键词
 */
	async findKeyWords() {
		let {ctx} = this
		this.ctx.validate({aid: "numstr"}, ctx.query)
		let keyWords = await this.KeyWord.findAll({
			where: {
				aid: ctx.query.aid
			},
			attributes: ["key_name", "trigger_type", "trigger_key", "update_at", "stat", "id"]
		})
		ctx.body = sendStat(this.constant.NORMAL, keyWords)
	}

	/**
 * // 搜索某个
 */
	async findKeyWord() {
		let {ctx} = this
		this.ctx.validate({aid: "pintstr", "id": "pintstr"}, ctx.query)
		let keyWord = await this.KeyWord.findOne({
			where: {
				aid: ctx.query.aid,
				id: ctx.query.id
			}
		})
		ctx.body = sendStat(this.constant.NORMAL, keyWord)
	}

	/**
	 * // 所有的 +搜索
	 */
	async getAllKfMsg() {
		let {ctx} = this
		let query = ctx.query
		// let model = this.app.model
		ctx.validate({
			aid: "numstr", nickname: {
				type: "string", required: false
			},
			oid: {
				type: "pintstr", required: false
			},
			respone_stat: {
				required: false,
				type: "enum",
				values: ["0", "1", undefined]
			}
		}, query)

		let queryStat = query.respone_stat != undefined ? {respone_stat: query.respone_stat} : {}
		let ids = []
		let queryObj = {}
		if (query.nickname) {
			queryObj = {
				nickname: {
					$like: "%" + query.nickname + "%"
				},
				aid: query.aid,
			}
		} else if (query.oid) {
			queryObj = {
				id: query.oid,
				aid: query.aid,
			}
		} else {
			queryObj = {
				aid: query.aid,
				// ...queryStat
			}
		}
		ids = await this.ApplicationUser.findAll({
			where: queryObj,
			attributes: ["id", "nickname", "headimg_url", "openid"]
		})
		if (ids.length == 0) {
			ctx.body = sendStat(this.constant.NORMAL, [])
			ctx.body.count = 0
			return
		}
		let user = {}
		ids.map((v) => {
			user[v.id] = v
		})
		let idList = Object.keys(user)
		// await this.app.redis.set(`mysql|user|aid=${query.aid}`,JSON.stringify(ids))

		let res = await this.UserKfMsgV.findAndCount({
			where: {
				oid: {
					$in: idList,
				},
				to_user: 0,
				...queryStat
			},
			limit: ctx.pageListNum,
			offset: ctx.startPage,
		})

		let msgRows = res.rows.map((msg) => {
			let msyObj = {
				msg: msg.msg,
				oid: msg.oid,
				id: msg.id,
				respone_stat: msg.respone_stat,
				create_at: msg.create_at
			}
			let u0 = user[msg.oid]
			if (u0) {
				msyObj.nickname = u0.nickname
				msyObj.headimg_url = u0.headimg_url
				msyObj.openid = u0.openid
			}
			return msyObj
		})// 连表
		ctx.body = sendStat(this.constant.NORMAL, msgRows)
		ctx.body.count = res.count
	}

	/**
	 * 响用户发消息
	 */
	async responseMsg() {
		let body = this.ctx.request.body
		this.ctx.validate({
			oid: "pintstr", msg: "jsonObject",
			response_type: ["1", "2", "3"]
		}, body)
		let obj = JSON.parse(body.msg)
		this.ctx.service.wechatUser.checkMsgObj(obj, body.response_type)
		let openid = await this.service.wechatUser.getUserOpenId(body.oid)

		await this.ctx.service.wechatUser.sendMsg(openid, JSON.parse(body.msg), body.response_type, body.oid)
		this.ctx.body = sendStat(this.constant.NORMAL)
		// 给指定发新信息// 记录
	}

	/**
	 * 设置已经回复
	 */
	async setHaveReply() {
		let body = this.ctx.request.body
		this.ctx.validate({msg_id: "pintstr"}, body)
		let v = await this.UserKfMsg.update({respone_stat: 1}, {
			where: {
				id: body.msg_id
			}
		})
		this.ctx.body = sendStat(this.constant.NORMAL, v)
	}

	/**
	 *  找到相应的用户对应的客服消息 客服 消息的 对应为id 0
	 */
	async getUserKfMsg() {

		let {ctx} = this
		this.ctx.validate({aid: "numstr", oid: "numstr"}, ctx.query)
		let {oid} = ctx.query
		let msgList = await this.UserKfMsg.findAll({
			order: [["create_at", "desc"]],
			where: {
				$or: [{
					to_user: oid,
					oid: 0,
				}, {
					to_user: 0,
					oid: oid,
				}]
			}
		})

		let datas = await this.ApplicationUser.findAll({
			attributes: ["nickname", "headimg_url", "id"],
			where: {
				id: oid
			}
		})
		let user = {}
		datas.map((v) => {
			user[v.id] = v
		})
		let msgListRes = msgList.map((msg) => {
			let u0 = user[msg.oid]
			if (u0) {
				return {
					oid: msg.oid,
					msg: msg.msg,
					create_at: msg.create_at,
					nickname: u0.nickname,
					headimg_url: u0.headimg_url
				}
			}
			return msg
		})// 连表
		ctx.body = sendStat(this.constant.NORMAL, msgListRes)
	}
}
module.exports = MsgController